package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author Tsuchi
 * @description TODO
 * @date 2024/12/24 18:34
 */
public class JwtUtil {

	// 过期时间常量 单位是毫秒
	private static long tokenExpiration = 7 * 60 * 60 * 1000L;

	// 加密密钥
	private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("5bc8e66e335ee7c7b3e641b6f091520e701d75de15d7".getBytes());

	// token生成
	public static String creatToken(Long userId, String username) {
		// 组装token
		String token = Jwts.builder()
			.setSubject("USER_INFO")
			.setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
			.claim("userId", userId)
			.claim("userName", username)
			.signWith(tokenSignKey)
			// .compressWith(CompressionCodecs.GZIP)
			.compact();
		return token;
	}

	public static Claims parseToken(String token) {
		try {
			Jws<Claims> claimsJws = Jwts.parserBuilder()
				.setSigningKey(tokenSignKey)
				.build()
				.parseClaimsJws(token);
			return claimsJws.getBody();
		} catch (ExpiredJwtException e) {
			throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
		} catch (JwtException e) {
			throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
		}


	}


	public static void main(String[] args) {
		String s = creatToken(1L, "Tsuchi");
		System.out.println(s);

		Claims claims = parseToken(s);
		System.out.println(claims);
	}
}
